package com.william.Example;

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.william.vloadingviewtool.LoadingViewTool;

public class WebViewActivity extends AppCompatActivity {

    private WebView webView;
    private LoadingViewTool tool;
    private boolean hasError;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        String url = "https://www.baidu.com/";
        this.webView = (WebView) findViewById(R.id.wv);

        this.tool = new LoadingViewTool(this.webView,true);

        this.webView.loadUrl(url);
        this.webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webView.loadUrl(url);
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Toast.makeText(WebViewActivity.this,"onPageStarted",Toast.LENGTH_SHORT).show();
                super.onPageStarted(view, url, favicon);
                hasError = false;
                View loadingView = LayoutInflater.from(WebViewActivity.this).inflate(R.layout.loading,null);
                tool.showLayout(loadingView);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Toast.makeText(WebViewActivity.this,"onPageFinished",Toast.LENGTH_SHORT).show();
                super.onPageFinished(view, url);

                if (!hasError) {
                    tool.restoreView();
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Toast.makeText(WebViewActivity.this,"onReceivedError",Toast.LENGTH_SHORT).show();

                hasError = true;
                View errorView = LayoutInflater.from(WebViewActivity.this).inflate(R.layout.error,null);
                Button btn = (Button) errorView.findViewById(R.id.btn);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        webView.reload();
                    }
                });
                tool.showLayout(errorView);
            }
        });
    }
}
